package com.settlement.system.controller;

import com.settlement.system.csv.CsvExportBuilder;
import com.settlement.system.csv.CsvExportUtil;
import com.settlement.system.common.enums.ExcelFileType;
import com.settlement.system.common.enums.WpBillAduitEnum;
import com.settlement.system.common.exception.ServiceException;
import com.settlement.system.model.entity.common.TblWpCheckOutConfig;
import com.settlement.system.model.entity.common.TblWpCheckOutDtl;
import com.settlement.system.service.IBaseService;
import com.settlement.system.service.ITblWpCheckOutConfigService;
import com.settlement.system.service.ITblWpCheckOutDtlService;
import com.settlement.system.service.csv.DateSpiltCsvDatas;
import com.settlement.system.common.util.common.FasUtil;
import com.alibaba.excel.context.AnalysisContext;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * WP-核查结果明细 前端控制器
 * @author xiaochuan
 * @since 2022-07-26
 */

@Slf4j
@Api(tags = "WP-核查结果明细",description = "WP-核查结果明细")
@RestController
@RequestMapping("/wp/tblWpCheckOutDtl")
public class TblWpCheckOutDtlController extends ExcelController<TblWpCheckOutDtl> {

    @Value("${system.export-root.path}")
    private String exportRootPath;

    @Resource
    private ITblWpCheckOutDtlService tblWpCheckOutDtlService;

    @Resource
    private ITblWpCheckOutConfigService tblWpCheckOutConfigService;

    @Override
    public IBaseService init() {
        return tblWpCheckOutDtlService;
    }

    @Override
    public Class<?> getModelClass() {
        return TblWpCheckOutDtl.class;
    }

    @Override
    protected void setParamsModel(Map<String, Object> model) {
        FasUtil.formatInQueryCondition(model, "poNo", "barCode", "billNo", "classify");
        FasUtil.toUpperCase(model, "poNo", "barCode", "billNo");
    }

    @Override
    public String verifyImportObject(TblWpCheckOutDtl detail, AnalysisContext analysisContext) {
        if("核查结果配置".equals(analysisContext.readSheetHolder().getSheetName())){
            return null;
        }
        String errorMsg = super.verifyImportObject(detail, analysisContext);
        if(StringUtils.isNotEmpty(errorMsg)){
            return errorMsg;
        }

        try{
            if(WpBillAduitEnum.CLASSIFY.TUIGONG_CHAYI.getNo().equals(detail.getClassify())){
                if(StringUtils.isEmpty(detail.getBillNo())){
                    return "分类=退供差异时，对应退供单号，必填";
                }
            }

            if(WpBillAduitEnum.FOLLOW_UP_DEPT.T9.getName().equals(detail.getFollowUpDept())){
                if(StringUtils.isEmpty(detail.getBlCheckDescript())){
                    return "当[跟进部门]为“有争议”时，百丽核查结果说明为必填";
                }
                if(StringUtils.isEmpty(detail.getWpCheckDescript())){
                    return "当[跟进部门]为“有争议”时，唯品核查结果说明为必填";
                }
            }
            if(WpBillAduitEnum.CHECK_RESULT.T28.getName().equals(detail.getCheckResult())){
                if(StringUtils.isEmpty(detail.getResponsibleParty())){
                    return "核查结果为“自认损失”时,责任方为不能为空";
                }
                if(StringUtils.isEmpty(detail.getLossReason())){
                    return "核查结果为“自认损失”时,损失原因不能为空";
                }
            }

            Map<String,Object> map = new HashMap<>();
            map.put("diffType",detail.getDiffType());
            List<TblWpCheckOutConfig> objects = tblWpCheckOutConfigService.selectByParam(map);
            if(CollectionUtils.isEmpty(objects)){
                return "差异类型="+detail.getDiffType()+" 未配置";
            }

            map = new HashMap<>();
            map.put("diffType",detail.getDiffType());
            map.put("followUpDept",detail.getFollowUpDept());
            objects = tblWpCheckOutConfigService.selectByParam(map);
            if(CollectionUtils.isEmpty(objects)){
                return "差异类型="+detail.getDiffType()+"、 跟进部门="+detail.getFollowUpDept()+" 未配置";
            }

            map = new HashMap<>();
            map.put("diffType",detail.getDiffType());
            map.put("checkResult",detail.getCheckResult());
            objects = tblWpCheckOutConfigService.selectByParam(map);
            if(CollectionUtils.isEmpty(objects)){
                return "差异类型="+detail.getDiffType()+"、 核查结果="+detail.getCheckResult()+" 未配置";
            }

            if(StringUtils.isNotEmpty(detail.getResponsibleParty())){
                map = new HashMap<>();
                map.put("diffType",detail.getDiffType());
                map.put("responsibleParty",detail.getResponsibleParty());
                objects = tblWpCheckOutConfigService.selectByParam(map);
                if(CollectionUtils.isEmpty(objects)){
                    return "差异类型="+detail.getDiffType()+"、 责任方="+detail.getResponsibleParty()+" 未配置";
                }
            }

            if(StringUtils.isNotEmpty(detail.getLossReason())){
                map = new HashMap<>();
                map.put("diffType",detail.getDiffType());
                map.put("lossReason",detail.getLossReason());
                objects = tblWpCheckOutConfigService.selectByParam(map);
                if(CollectionUtils.isEmpty(objects)){
                    return "差异类型="+detail.getDiffType()+"、 损失原因="+detail.getLossReason()+" 未配置";
                }
            }

        } catch (Exception ex) {
            log.error("system error:", ex);
            return "系统异常";
        }

        return null;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    protected void saveData(List<TblWpCheckOutDtl> datas,AnalysisContext analysisContext) throws ServiceException {
        try{
            if("核查结果配置".equals(analysisContext.readSheetHolder().getSheetName())){
                return;
            }
            tblWpCheckOutDtlService.saveNoDuplicateList(datas);
        }catch (Exception ex){
            log.error("导入数据异常", ex);
            throw new ServiceException("导入数据异常", ex);
        }
    }

    @Override
    protected String validateAllDate(List<TblWpCheckOutDtl> datas,AnalysisContext analysisContext) {
        if("核查结果配置".equals(analysisContext.readSheetHolder().getSheetName())){
            return null;
        }
        List<String> list = new ArrayList<>();
        for(TblWpCheckOutDtl data : datas){
            String toString = data.toString();
            if(list.contains(toString)){
                return "有两行数据重复";
            }else{
                list.add(toString);
            }
        }
        return null;
    }

    @Override
    public void exportExcelPost(HttpServletRequest request, HttpServletResponse response, @RequestBody Map<String, Object> params) throws Exception {
        setParamsModel(params);
        String fileName = "WP-核查结果明细";
        String path = exportRootPath + System.currentTimeMillis() + File.separator;
        CsvExportUtil.createCsv()
                .headClass(TblWpCheckOutDtl.class)
                .fileName(fileName)
                .fileType(ExcelFileType.XLSX)
                .model(CsvExportBuilder.MULTI_ZIP_MODEL)
                .parentPath(path)
                .csvDatas(new DateSpiltCsvDatas(tblWpCheckOutDtlService, params))
                .export(request, response);
    }



}

